﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LotteryVote.Data;
using LotteryVote.Entity;
using LotteryVote.Logic.Exceptions;
using LotteryVote.Utility;

namespace LotteryVote.Logic
{
    public class ShareRateFacade
    {
        private UserDataAccess _daUser;
        internal UserDataAccess DaUser
        {
            get
            {
                if (_daUser == null)
                    _daUser = new UserDataAccess();
                return _daUser;
            }
            set
            {
                _daUser = value;
            }
        }

        public ShareRateInfo GetShareRateByMember(int userId)
        {
            var user = DaUser.GetUserById(userId);
            if (user == null)
                throw new InvalidDataException("Invalid User");
            if (user.Role == SystemRole.Guest)
                return GetShareRateByAgent(user.ParentId);
            else
                throw new InvalidRoleException(SystemRole.Guest, user.Role);

        }
        public ShareRateInfo GetShareRateByAgent(int userId)
        {
            var user = DaUser.GetUserById(userId);
            if (user == null)
                throw new InvalidDataException("Invalid User");
            if (user.Role == SystemRole.Agent)
                return GetShareRate(user);
            else
                throw new InvalidRoleException(SystemRole.Agent, user.Role);
        }
        private ShareRateInfo GetShareRate(User user)
        {
            var master = DaUser.GetUserById(user.ParentId);
            var super = DaUser.GetUserById(master.ParentId);
            var company = DaUser.GetUserById(super.ParentId);

            ShareRateItem companyShareRate = new ShareRateItem(company, GetShareRate(company, super));
            ShareRateItem superShareRate = new ShareRateItem(super, GetShareRate(super, master));
            ShareRateItem masterShareRate = new ShareRateItem(master, GetShareRate(master, user));
            ShareRateItem agentShareRate = new ShareRateItem(user, user.UserInfo.ShareRate);

            ShareRateInfo shareRate = new ShareRateInfo
            {
                CompanyShareRate = companyShareRate,
                SuperShareRate = superShareRate,
                MasterShareRate = masterShareRate,
                AgentShareRate = agentShareRate
            };
            return shareRate;
        }
        private double GetShareRate(User user, User child)
        {
            return user.UserInfo.ShareRate - child.UserInfo.ShareRate;
        }
    }
}
